﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Data.SqlClient;
using System.Xml;
using Library;
using DevComponents.AdvTree;
using System.IO;

namespace QuanLyThi.BienSoanDeThi
{
    public partial class FrmCauHoiTongQuat : Form
    {
        bool Xem = false;
        int IDCauHoiCha = 0;
        string mondaotao = "";
        public FrmCauHoiTongQuat(string mondaotao)
        {
            InitializeComponent();            
            this.mondaotao = mondaotao;
            this.BindTree(mondaotao);
        }

        public FrmCauHoiTongQuat(string mondaotao,bool Xem,int IDCauHoiCha)
        {
            InitializeComponent();
            this.Xem = true;
            this.mondaotao = mondaotao;
            this.IDCauHoiCha = IDCauHoiCha;
          
            butThemCauHoiCon.Visible = false;
            btCauHoiChinh.Visible = false;
            butXoaCauHoiChinh.Visible = false;
            butSuaCauHoiChinh.Visible = false;
            tree.Visible = false;
            this.NoiDungXem();
            label1.Text = "NỘI DUNG CÂU HỎI SỐ " + IDCauHoiCha;


            //Dinh dang lai cach hien thi
            this.noidung.Location = new System.Drawing.Point(0, 142);          
            this.noidung.Size = new System.Drawing.Size(793, 418);
            this.panel3.Location = new System.Drawing.Point(1, 87);         
            this.panel3.Size = new System.Drawing.Size(796, 23);
            this.lblcau.Location = new System.Drawing.Point(3, 4);         
            this.lblcau.Size = new System.Drawing.Size(151, 16);

            this.tb1.ButtonSize = new System.Drawing.Size(16, 16); 
            this.tb1.Location = new System.Drawing.Point(1, 110); 
            this.tb1.Size = new System.Drawing.Size(608, 26);
        }


        void NoiDungXem()
        {
            try
            {
                msql = "select [NoiDung]" +
                       "   from tb_CauHoiCha" +
                       "   where Ms_Mondaotao=" + mondaotao + " and IDCauHoiCha=" + IDCauHoiCha;
                DataTable dt = mLibrary.GetDataTable(msql, "a");
                if (dt.Rows.Count > 0)
                {
                    LoadNoidung(noidung, (byte[])dt.Rows[0]["noidung"]);
                    butThemCauHoiCon.Text = "Các câu hỏi con của câu " + IDCauHoiCha;
                }
                else
                {
                    noidung.Clear();
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("Xem lại,có lỗi xãy ra", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        public static string mConnect = FrmMain.mConnect;
        private string msql = "";
        public DGC_Library mLibrary = new DGC_Library(mConnect);





        private RichTextBox rtbTemp = new RichTextBox();
        public event System.EventHandler Stamp;
        public event System.EventHandler SelChanged;

        Color m_StampColor = Color.Blue;

        [Description("Color of the stamp text"),
        Category("Appearance")]
        public Color StampColor
        {
            get { return m_StampColor; }
            set { m_StampColor = value; }
        }


        StampActions m_StampAction = StampActions.EditedBy;
        [Description("Determines how the stamp button will respond"),
        Category("Behavior")]
        public StampActions StampAction
        {
            get { return m_StampAction; }
            set { m_StampAction = value; }
        }

        protected virtual void OnStamp(EventArgs e)
        {

            RichTextBox rt = new RichTextBox();
            //Duyet cac control dang duoc FOCUS
            if (noidung.Focused) rt = noidung;

         







            if (Stamp != null)
                Stamp(this, e);

            switch (StampAction)
            {
                case StampActions.EditedBy:
                    {
                        StringBuilder stamp = new StringBuilder(""); //holds our stamp text
                        if (rt.Text.Length > 0) stamp.Append("\r\n\r\n"); //add two lines for space
                        stamp.Append("Edited by ");
                        //use the CurrentPrincipal name if one exsist else use windows logon username
                        if (Thread.CurrentPrincipal == null || Thread.CurrentPrincipal.Identity == null || Thread.CurrentPrincipal.Identity.Name.Length <= 0)
                            stamp.Append(Environment.UserName);
                        else
                            stamp.Append(Thread.CurrentPrincipal.Identity.Name);
                        stamp.Append(" on " + DateTime.Now.ToLongDateString() + "\r\n");

                        rt.SelectionLength = 0; //unselect everything basicly
                        rt.SelectionStart = rt.Text.Length; //start new selection at the end of the text
                        rt.SelectionColor = this.StampColor; //make the selection blue
                        rt.SelectionFont = new Font(rt.SelectionFont, FontStyle.Bold); //set the selection font and style
                        rt.AppendText(stamp.ToString()); //add the stamp to the richtextbox
                        rt.Focus(); //set focus back on the richtextbox
                    } break; //end edited by stamp
                case StampActions.DateTime:
                    {
                        StringBuilder stamp = new StringBuilder(""); //holds our stamp text
                        if (rt.Text.Length > 0) stamp.Append("\r\n\r\n"); //add two lines for space
                        stamp.Append(DateTime.Now.ToLongDateString() + "\r\n");
                        rt.SelectionLength = 0; //unselect everything basicly
                        rt.SelectionStart = rt.Text.Length; //start new selection at the end of the text
                        rt.SelectionColor = this.StampColor; //make the selection blue
                        rt.SelectionFont = new Font(rt.SelectionFont, FontStyle.Bold); //set the selection font and style
                        rt.AppendText(stamp.ToString()); //add the stamp to the richtextbox
                        rt.Focus(); //set focus back on the richtextbox
                    } break;
            } //end select
        }



        #region Change font
        /// <summary>
        ///     Change the richtextbox font for the current selection
        /// </summary>
        public void ChangeFont(string fontFamily)
        {
            RichTextBox rt = new RichTextBox();
            //Duyet cac control dang duoc FOCUS
            if (noidung.Focused) rt = noidung;

           

            //This method should handle cases that occur when multiple fonts/styles are selected
            // Parameters:-
            // fontFamily - the font to be applied, eg "Courier New"

            // Reason: The reason this method and the others exist is because
            // setting these items via the selection font doen't work because
            // a null selection font is returned for a selection with more 
            // than one font!

            int rtb1start = rt.SelectionStart;
            int len = rt.SelectionLength;
            int rtbTempStart = 0;

            // If len <= 1 and there is a selection font, amend and return
            if (len <= 1 && rt.SelectionFont != null)
            {
                rt.SelectionFont =
                    new Font(fontFamily, rt.SelectionFont.Size, rt.SelectionFont.Style);
                return;
            }

            // Step through the selected text one char at a time
            rtbTemp.Rtf = rt.SelectedRtf;
            for (int i = 0; i < len; ++i)
            {
                rtbTemp.Select(rtbTempStart + i, 1);
                rtbTemp.SelectionFont = new Font(fontFamily, rtbTemp.SelectionFont.Size, rtbTemp.SelectionFont.Style);
            }

            // Replace & reselect
            rtbTemp.Select(rtbTempStart, len);
            rt.SelectedRtf = rtbTemp.SelectedRtf;
            rt.Select(rtb1start, len);
            return;
        }
        #endregion

        #region Change font style
        /// <summary>
        ///     Change the richtextbox style for the current selection
        /// </summary>
        public void ChangeFontStyle(FontStyle style, bool add, RichTextBox rtb1)
        {
            //This method should handle cases that occur when multiple fonts/styles are selected
            // Parameters:-
            //	style - eg FontStyle.Bold
            //	add - IF true then add else remove

            // throw error if style isn't: bold, italic, strikeout or underline
            if (style != FontStyle.Bold
                && style != FontStyle.Italic
                && style != FontStyle.Strikeout
                && style != FontStyle.Underline)
                throw new System.InvalidProgramException("Invalid style parameter to ChangeFontStyle");

            int rtb1start = rtb1.SelectionStart;
            int len = rtb1.SelectionLength;
            int rtbTempStart = 0;

            //if len <= 1 and there is a selection font then just handle and return
            if (len <= 1 && rtb1.SelectionFont != null)
            {
                //add or remove style 
                if (add)
                    rtb1.SelectionFont = new Font(rtb1.SelectionFont, rtb1.SelectionFont.Style | style);
                else
                    rtb1.SelectionFont = new Font(rtb1.SelectionFont, rtb1.SelectionFont.Style & ~style);

                return;
            }

            // Step through the selected text one char at a time	
            rtbTemp.Rtf = rtb1.SelectedRtf;
            for (int i = 0; i < len; ++i)
            {
                rtbTemp.Select(rtbTempStart + i, 1);

                //add or remove style 
                if (add)
                    rtbTemp.SelectionFont = new Font(rtbTemp.SelectionFont, rtbTemp.SelectionFont.Style | style);
                else
                    rtbTemp.SelectionFont = new Font(rtbTemp.SelectionFont, rtbTemp.SelectionFont.Style & ~style);
            }

            // Replace & reselect
            rtbTemp.Select(rtbTempStart, len);
            rtb1.SelectedRtf = rtbTemp.SelectedRtf;
            rtb1.Select(rtb1start, len);
            return;
        }
        #endregion

        #region Change font size
        /// <summary>
        ///     Change the richtextbox font size for the current selection
        /// </summary>
        public void ChangeFontSize(float fontSize)
        {
            RichTextBox rt = new RichTextBox();
            //Duyet cac control dang duoc FOCUS
            if (noidung.Focused) rt = noidung;

          

            //This method should handle cases that occur when multiple fonts/styles are selected
            // Parameters:-
            // fontSize - the fontsize to be applied, eg 33.5

            if (fontSize <= 0.0)
                throw new System.InvalidProgramException("Invalid font size parameter to ChangeFontSize");

            int rtb1start = rt.SelectionStart;
            int len = rt.SelectionLength;
            int rtbTempStart = 0;

            // If len <= 1 and there is a selection font, amend and return
            if (len <= 1 && rt.SelectionFont != null)
            {
                rt.SelectionFont =
                    new Font(rt.SelectionFont.FontFamily, fontSize, rt.SelectionFont.Style);
                return;
            }

            // Step through the selected text one char at a time
            rtbTemp.Rtf = rt.SelectedRtf;
            for (int i = 0; i < len; ++i)
            {
                rtbTemp.Select(rtbTempStart + i, 1);
                rtbTemp.SelectionFont = new Font(rtbTemp.SelectionFont.FontFamily, fontSize, rtbTemp.SelectionFont.Style);
            }

            // Replace & reselect
            rtbTemp.Select(rtbTempStart, len);
            rt.SelectedRtf = rtbTemp.SelectedRtf;
            rt.Select(rtb1start, len);
            return;
        }
        #endregion

        #region Change font color
        /// <summary>
        ///     Change the richtextbox font color for the current selection
        /// </summary>
        public void ChangeFontColor(Color newColor, RichTextBox rt)
        {



            //This method should handle cases that occur when multiple fonts/styles are selected
            // Parameters:-
            //	newColor - eg Color.Red

            int rtb1start = rt.SelectionStart;
            int len = rt.SelectionLength;
            int rtbTempStart = 0;

            //if len <= 1 and there is a selection font then just handle and return
            if (len <= 1 && rt.SelectionFont != null)
            {
                rt.SelectionColor = newColor;
                return;
            }

            // Step through the selected text one char at a time	
            rtbTemp.Rtf = rt.SelectedRtf;
            for (int i = 0; i < len; ++i)
            {
                rtbTemp.Select(rtbTempStart + i, 1);

                //change color
                rtbTemp.SelectionColor = newColor;
            }

            // Replace & reselect
            rtbTemp.Select(rtbTempStart, len);
            rt.SelectedRtf = rtbTemp.SelectedRtf;
            rt.Select(rtb1start, len);
            return;
        }
        #endregion



        public Font GetFontDetails(RichTextBox rt)
        {
            //This method should handle cases that occur when multiple fonts/styles are selected

            int rtb1start = rt.SelectionStart;
            int len = rt.SelectionLength;
            int rtbTempStart = 0;

            if (len <= 1)
            {
                // Return the selection or default font
                if (rt.SelectionFont != null)
                    return rt.SelectionFont;
                else
                    return rt.Font;
            }

            // Step through the selected text one char at a time	
            // after setting defaults from first char
            rtbTemp.Rtf = rt.SelectedRtf;

            //Turn everything on so we can turn it off one by one
            FontStyle replystyle =
                FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout | FontStyle.Underline;

            // Set reply font, size and style to that of first char in selection.
            rtbTemp.Select(rtbTempStart, 1);
            string replyfont = rtbTemp.SelectionFont.Name;
            float replyfontsize = rtbTemp.SelectionFont.Size;
            replystyle = replystyle & rtbTemp.SelectionFont.Style;

            // Search the rest of the selection
            for (int i = 1; i < len; ++i)
            {
                rtbTemp.Select(rtbTempStart + i, 1);

                // Check reply for different style
                replystyle = replystyle & rtbTemp.SelectionFont.Style;

                // Check font
                if (replyfont != rtbTemp.SelectionFont.FontFamily.Name)
                    replyfont = "";

                // Check font size
                if (replyfontsize != rtbTemp.SelectionFont.Size)
                    replyfontsize = (float)0.0;
            }

            // Now set font and size if more than one font or font size was selected
            if (replyfont == "")
                replyfont = rtbTemp.Font.FontFamily.Name;

            if (replyfontsize == 0.0)
                replyfontsize = rtbTemp.Font.Size;

            // generate reply font
            Font reply
                = new Font(replyfont, replyfontsize, replystyle);

            return reply;
        }



        private void tb1_ButtonClick(object sender, ToolBarButtonClickEventArgs e)
        {
            RichTextBox rt = new RichTextBox();
            //Duyet cac control dang duoc FOCUS
            if (noidung.Focused) rt = noidung;  

            // true if style to be added
            // false to remove style
            bool add = e.Button.Pushed;

            //Switch based on the tag of the button pressed
            switch (e.Button.Tag.ToString().ToLower())
            {
                case "font":
                    ChangeFont(tbbFont.Text);
                    break;
                case "font size":
                    ChangeFontSize(float.Parse(tbbFontSize.Text));
                    break;

                case "bold":
                    ChangeFontStyle(FontStyle.Bold, add, rt);
                    break;
                case "italic":
                    ChangeFontStyle(FontStyle.Italic, add, rt);
                    break;
                case "underline":
                    ChangeFontStyle(FontStyle.Underline, add, rt);
                    break;
                case "strikeout":
                    ChangeFontStyle(FontStyle.Strikeout, add, rt);
                    break;
                case "left":
                    //change horizontal alignment to left
                    rt.SelectionAlignment = HorizontalAlignment.Left;
                    tbbCenter.Pushed = false;
                    tbbRight.Pushed = false;
                    break;
                case "center":
                    //change horizontal alignment to center
                    tbbLeft.Pushed = false;
                    rt.SelectionAlignment = HorizontalAlignment.Center;
                    tbbRight.Pushed = false;
                    break;
                case "right":
                    //change horizontal alignment to right
                    tbbLeft.Pushed = false;
                    tbbCenter.Pushed = false;
                    rt.SelectionAlignment = HorizontalAlignment.Right;
                    break;
                case "edit stamp":
                    OnStamp(new EventArgs()); //send stamp event
                    break;
                case "color":
                    rt.SelectionColor = Color.Black;
                    break;
                case "undo":
                    rt.Undo();
                    break;
                case "redo":
                    rt.Redo();
                    break;
                case "open":
                    try
                    {
                        if (ofd1.ShowDialog() == DialogResult.OK && ofd1.FileName.Length > 0)
                            if (System.IO.Path.GetExtension(ofd1.FileName).ToLower().Equals(".rtf"))
                                rt.LoadFile(ofd1.FileName, RichTextBoxStreamType.RichText);
                            else
                                rt.LoadFile(ofd1.FileName, RichTextBoxStreamType.PlainText);
                    }
                    catch (ArgumentException ae)
                    {
                        if (ae.Message == "Invalid file format.")
                            MessageBox.Show("There was an error loading the file: " + ofd1.FileName);
                    }
                    break;
                case "save":
                    if (sfd1.ShowDialog() == DialogResult.OK && sfd1.FileName.Length > 0)
                        if (System.IO.Path.GetExtension(sfd1.FileName).ToLower().Equals(".rtf"))
                            rt.SaveFile(sfd1.FileName);
                        else
                            rt.SaveFile(sfd1.FileName, RichTextBoxStreamType.PlainText);
                    break;
                case "cut":
                    {
                        if (rt.SelectedText.Length <= 0) break;
                        rt.Cut();
                        break;
                    }
                case "copy":
                    {
                        if (rt.SelectedText.Length <= 0) break;
                        rt.Copy();
                        break;
                    }
                case "paste":
                    {
                        try
                        {
                            rt.Paste();
                        }
                        catch
                        {
                            MessageBox.Show("Paste Failed");
                        }
                        break;
                    }
                case "image":
                    {
                        OpenFileDialog _dialog = new OpenFileDialog();
                        _dialog.Filter = "All Image Files|*.bmp;*.ico;*.gif;*.jpeg;*.jpg;*.png;*.tif;*.tiff|" +
                                         "Windows Bitmap(*.bmp)|*.bmp|" +
                                         "Windows Icon(*.ico)|*.ico|" +
                                         "Graphics Interchange Format (*.gif)|(*.gif)|" +
                                         "JPEG File Interchange Format (*.jpg)|*.jpg;*.jpeg|" +
                                         "Portable Network Graphics (*.png)|*.png|" +
                                         "Tag Image File Format (*.tif)|*.tif;*.tiff";
                        if (DialogResult.OK == _dialog.ShowDialog(this))
                        {
                            try
                            {
                                //// If file is an icon
                                //if (_dialog.FileName.ToUpper().EndsWith(".ICO"))
                                //{
                                //    // Create a new icon, get it's handle, and create a bitmap from
                                //    // its handle
                                //    rtBox_Main.InsertImage(Bitmap.FromHicon((new Icon(_dialog.FileName)).Handle));
                                //}
                                //else
                                //{
                                //    // Create a bitmap from the filename
                                //    rtBox_Main.InsertImage(Image.FromFile(_dialog.FileName));
                                //}


                                Image img = Image.FromFile(_dialog.FileName);
                                IDataObject orgData = Clipboard.GetDataObject();
                                Clipboard.SetImage(img);
                                rt.Paste();
                            }
                            catch (Exception _e)
                            {
                                MessageBox.Show("The file could not be opened:\n\n" + _e.Message, "File Open Error");
                            }
                        }
                        break;
                    }

                case "word":
                    {
                        OpenFileDialog _dialog = new OpenFileDialog();
                        _dialog.Filter = "Word File|*.rtf";

                        if (DialogResult.OK == _dialog.ShowDialog(this))
                        {
                            try
                            {

                                rt.LoadFile(_dialog.FileName);
                            }
                            catch (Exception _e)
                            {
                                MessageBox.Show("The file could not be opened:\n\n" + _e.Message, "File Open Error");
                            }
                        }
                        break;
                    }
                case "math":
                    {

                        try
                        {

                            System.Diagnostics.Process Proc = new System.Diagnostics.Process();
                            Proc.StartInfo.FileName = Application.StartupPath + "\\MathType\\MathType.exe";
                            Proc.Start();
                        }
                        catch (Exception _e)
                        {
                            MessageBox.Show("Không thể thực thi:\n\n" + _e.Message, "Thông báo");
                        }

                        break;
                    }
            } //end select
        }

        #region Keyboard Handler
        private void noidung_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            RichTextBox rt = new RichTextBox();
            //Duyet cac control dang duoc FOCUS
            if (noidung.Focused) rt = noidung;

           



            if (e.Modifiers == Keys.Control)
            {
                ToolBarButton tbb = null;

                switch (e.KeyCode)
                {
                    case Keys.B:
                        tbb = this.tbbBold;
                        break;
                    case Keys.I:
                        tbb = this.tbbItalic;
                        break;
                    case Keys.S:
                        tbb = this.tbbStamp;
                        break;
                    case Keys.U:
                        tbb = this.tbbUnderline;
                        break;
                    case Keys.OemMinus:
                        tbb = this.tbbStrikeout;
                        break;
                }

                if (tbb != null)
                {
                    if (e.KeyCode != Keys.S) tbb.Pushed = !tbb.Pushed;
                    tb1_ButtonClick(null, new ToolBarButtonClickEventArgs(tbb));
                }
            }

            //Insert a tab if the tab key was pressed.
            /* NOTE: This was needed because in rtb1_KeyPress I tell the richtextbox not
             * to handle tab events.  I do that because CTRL+I inserts a tab for some
             * strange reason.  What was MicroSoft thinking?
             * Richard Parsons 02/08/2007
             */
            if (e.KeyCode == Keys.Tab)
                rt.SelectedText = "\t";

        }

        private void noidung_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if ((int)e.KeyChar == 9)
                e.Handled = true; // Stops Ctrl+I from inserting a tab (char HT) into the richtextbox
        }


        #endregion
        #region Link Clicked
        /// <summary>
        /// Starts the default browser if a link is clicked
        /// </summary>
        private void noidung_LinkClicked(object sender, System.Windows.Forms.LinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(e.LinkText);
        }
        #endregion
        public void UpdateToolbar()
        {
            RichTextBox rt = new RichTextBox();
            //Duyet cac control dang duoc FOCUS
            if (noidung.Focused) rt = noidung;

            







            // Get the font, fontsize and style to apply to the toolbar buttons
            Font fnt = GetFontDetails(rt);
            // Set font style buttons to the styles applying to the entire selection
            FontStyle style = fnt.Style;

            //Set all the style buttons using the gathered style
            tbbBold.Pushed = fnt.Bold; //bold button
            tbbItalic.Pushed = fnt.Italic; //italic button
            tbbUnderline.Pushed = fnt.Underline; //underline button
            tbbStrikeout.Pushed = fnt.Strikeout; //strikeout button
            tbbLeft.Pushed = (rt.SelectionAlignment == HorizontalAlignment.Left); //justify left
            tbbCenter.Pushed = (rt.SelectionAlignment == HorizontalAlignment.Center); //justify center
            tbbRight.Pushed = (rt.SelectionAlignment == HorizontalAlignment.Right); //justify right

            //Check the correct color
            foreach (MenuItem mi in cmColors.MenuItems)
                mi.Checked = (rt.SelectionColor == Color.FromName(mi.Text));

            //Check the correct font
            foreach (MenuItem mi in cmFonts.MenuItems)
                mi.Checked = (fnt.FontFamily.Name == mi.Text);

            //Check the correct font size
            foreach (MenuItem mi in cmFontSizes.MenuItems)
                mi.Checked = ((int)fnt.SizeInPoints == float.Parse(mi.Text));
        }
        private void noidung_SelectionChanged(object sender, EventArgs e)
        {
            //Update the toolbar buttons
            UpdateToolbar();

            //Send the SelChangedEvent
            if (SelChanged != null)
                SelChanged(this, e);
        }

        public static byte[] StrToByteArray(string str)
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            return encoding.GetBytes(str);
        }

        private void InsertDatabase(RichTextBox rt)
        {
            string strQuery = "exec Luu_CauHoiCha @Ms_mondaotao, " +                     
                              "@noidung";
            SqlCommand cmd = new SqlCommand(strQuery);
            cmd.Parameters.Add("@Ms_mondaotao", SqlDbType.Int).Value = mondaotao;     
            cmd.Parameters.Add("@noidung", SqlDbType.Image).Value = StrToByteArray(rt.Rtf);       
           
         
            InsertUpdateData(cmd);
        }

        private Boolean InsertUpdateData(SqlCommand cmd)
        {
            SqlConnection con = new SqlConnection(mConnect);
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
        }


        private void btCauHoiChinh_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dialog = MessageBox.Show("Bạn có muốn thêm thông tin câu hỏi tổng quát này không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialog == DialogResult.Yes)
                {
                    //Lưu cau hoi lai

                    InsertDatabase(noidung);                   
                   
                    MessageBox.Show("Lưu thông tin câu hỏi thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.BindTree(mondaotao);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Lưu thông tin câu hỏi không thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
      
        public void BindTree(string mondaotao)
        {
            try
            {
                tree.Nodes.Clear();
                tree.ExpandAll();
                msql = "select [NoiDung],[Ms_Mondaotao],[IDCauHoiCha],('Câu '+cast([IDCauHoiCha] as nvarchar)) as Ten" +
                     "   from tb_CauHoiCha" +
                     "   where Ms_Mondaotao=" + mondaotao;
                
                DataTable dtCha = mLibrary.GetDataTable(msql, "Cha");
                foreach (DataRow row in dtCha.Rows)
                {
                    //Cau hoi cha
                    Node nodeCha = new Node();
                    nodeCha.Tag = row["IDCauHoiCha"].ToString();
                    nodeCha.Text = row["Ten"].ToString();

                    nodeCha.ExpandAll();
                    tree.Nodes.Add(nodeCha);
                    //Thêm Node Cau hoi con
                    msql = "SELECT distinct Cauhoi, (N'Câu hỏi ' +cast(Cauhoi as nvarchar)) Ten " +
                           " FROM [tb_Nganhangdethi]" +
                           " where CauHoiCha=1 and IDCauHoiCha=" + nodeCha.Tag;
                
                    DataTable dtCon = mLibrary.GetDataTable(msql, "Con");
                    foreach (DataRow rowCon in dtCon.Rows)
                    {
                        //Cau hoi cha
                        Node nodeCon = new Node();
                        nodeCon.Tag = rowCon["Cauhoi"].ToString();
                        nodeCon.Text = rowCon["Ten"].ToString();

                        nodeCon.ExpandAll();
                        nodeCha.Nodes.Add(nodeCon);
                    }
                }
            }
            catch (Exception ex)
            {
                
            }
        }
        private void LoadNoidung(RichTextBox rt, byte[] noidung)
        {
            Stream theFile = new MemoryStream(noidung);
            rt.LoadFile(theFile, RichTextBoxStreamType.RichText);
        }

        private void tree_NodeClick(object sender, TreeNodeMouseEventArgs e)
        {
            try
            {
                msql = "select [NoiDung]" +
                       "   from tb_CauHoiCha" +
                       "   where Ms_Mondaotao=" + mondaotao + " and IDCauHoiCha=" + tree.SelectedNode.Tag.ToString();
                DataTable dt = mLibrary.GetDataTable(msql, "a");
                if (tree.SelectedNode.Level == 0)//Cha
                {
                    LoadNoidung(noidung, (byte[])dt.Rows[0]["noidung"]);
                    butThemCauHoiCon.Text = "Các câu hỏi con của câu " + tree.SelectedNode.Tag.ToString();
                }
                else
                {
                    noidung.Clear();
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("Xem lại,có lỗi xãy ra", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void butSuaCauHoiChinh_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dialog = MessageBox.Show("Bạn có muốn sửa thông tin câu hỏi này không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialog == DialogResult.Yes)
                {
                    if (tree.SelectedNode != null)
                    {

                        //Lưu cau hoi lai
                        UpdateDatabase(noidung, int.Parse(tree.SelectedNode.Tag.ToString()));

                        MessageBox.Show("Sửa thông tin câu hỏi thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Sửa thông tin câu hỏi không thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void UpdateDatabase(RichTextBox rt, int IDCauHoiCha)
        {
            string strQuery = "exec Sua_CauHoiCha @IDCauHoiCha, " +
                             "@noidung";
            SqlCommand cmd = new SqlCommand(strQuery);
            cmd.Parameters.Add("@IDCauHoiCha", SqlDbType.Int).Value = IDCauHoiCha;
            cmd.Parameters.Add("@noidung", SqlDbType.Image).Value = StrToByteArray(rt.Rtf);


            InsertUpdateData(cmd);
        }

        private void butXoaCauHoiChinh_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dialog = MessageBox.Show("Bạn có muốn xóa thông tin câu hỏi này không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialog == DialogResult.Yes)
                {
                    if (tree.SelectedNode != null)
                    {

                        //Lưu cau hoi lai
                        msql = "Delete from tb_Cauhoicha where IDCauHoiCha=" + int.Parse(tree.SelectedNode.Tag.ToString());
                        mLibrary.RunProc(msql);
                        MessageBox.Show("Xóa thông tin câu hỏi thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.BindTree(mondaotao);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Xóa thông tin câu hỏi không thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

      
        private void butThemCauHoiCon_Click(object sender, EventArgs e)
        {
            try
            {
                int IDCha= int.Parse(tree.SelectedNode.Tag.ToString());
                FrmCauHoiCon frm = new FrmCauHoiCon(mondaotao,IDCha);
                frm.ShowDialog();
                BindTree(mondaotao);
            }
            catch (Exception)
            {
                
                throw;
            }
          
        }





    }
}
